﻿using System;
using System.IO;
using Windows.Storage.Streams;

namespace TakePhotoTogether
{
    public class RandomStream : IRandomAccessStream
    {
        public Stream InternStream { get; protected set; }

        public RandomStream(Stream underlyingstream)
        {
            InternStream = underlyingstream;
        }

        public bool CanRead
        {
            get { return this.InternStream.CanRead; }
        }

        public bool CanWrite
        {
            get { return this.InternStream.CanWrite; }
        }

        public IRandomAccessStream CloneStream()
        {
            throw new NotImplementedException();
        }

        public IInputStream GetInputStreamAt(ulong position)
        {
            //THANKS Microsoft! This is GREATLY appreciated!
            InternStream.Position = (long)position;
            return InternStream.AsInputStream();
        }

        public IOutputStream GetOutputStreamAt(ulong position)
        {
            InternStream.Position = (long)position;
            return InternStream.AsOutputStream();
        }

        public ulong Position
        {
            get { return (ulong)this.InternStream.Position; }
        }

        public void Seek(ulong position)
        {
            this.InternStream.Seek((long)position, SeekOrigin.Begin);
        }

        public ulong Size
        {
            get
            {
                return (ulong)InternStream.Length;
            }
            set
            {
                InternStream.SetLength((long)value);
            }
        }

        public void Dispose()
        {
            this.InternStream.Dispose();
        }

        public Windows.Foundation.IAsyncOperationWithProgress<IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options)
        {
            return this.GetInputStreamAt(this.Position).ReadAsync(buffer, count, options);
        }

        public Windows.Foundation.IAsyncOperation<bool> FlushAsync()
        {
            return this.GetOutputStreamAt(this.Position).FlushAsync();
        }

        public Windows.Foundation.IAsyncOperationWithProgress<uint, uint> WriteAsync(IBuffer buffer)
        {
            return this.GetOutputStreamAt(this.Position).WriteAsync(buffer);
        }
    }
}
